package com.salinity.kun.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class ToUtf8 {
	public static void main(String args[]) {
		Path filesDirectory = Paths.get("E:\\DEVELOPERKIT\\practice\\java\\saltyCode");
		try {
			convetToUtf8(filesDirectory);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void convetToUtf8(Path filePath) throws Exception {
		String filename = filePath.getFileName().toString();
		if (!filePath.toFile().exists()||filename.startsWith(".")) {
			return;
		}
	
		if (filePath.toFile().isDirectory()) {
			File[] fileArray = filePath.toFile().listFiles();
			for (File file : fileArray) {
				convetToUtf8(file.toPath());
			}
		} else {
			if(filePath.getFileName().toString().endsWith(".java")){
				System.out.println("Handle: "+filePath.toString());
				String charset = encoder(filePath);
				if (!charset.equals("UTF-8")) {
					try (BufferedReader br = new BufferedReader(
							new InputStreamReader(new FileInputStream(filePath.toFile()), charset));
							BufferedWriter bw = Files.newBufferedWriter(filePath, StandardOpenOption.WRITE)) {

						String line;
						while ((line = br.readLine()) != null) {
							bw.write(new String(line.getBytes(), "UTF-8"));
							bw.newLine();
						}

					}
				}
			}
		}

	}

	public static String encoder(Path filePath) throws Exception {
		String code = null;
		try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(filePath.toFile()))) {
			int binRead = in.read();
			int handle = binRead << 8;
			int p = handle + in.read();
			switch (p) {
			case 0xefbb:
				code = "UTF-8";
				break;
			case 0xfffe:
				code = "Unicode";
				break;
			case 0xfeff:
				code = "UTF-16BE";
				break;
			default:
				code = "GBK";
			}
		}
		return code;
	}

}
